from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
# Create your views here.
from utils.goods import get_categories
from apps.contents.models import ContentCategory, Content
class IndexView(View):
    def get(self, request):
        """提供首页视图"""
        # 获取商品频道和分类
        categories = get_categories()
        # 广告数据
        contents = {}
        content_categories = ContentCategory.objects.all()
        for cat in content_categories:
            # 筛选出状态为True的广告,content_set是ContentCategory模型类中的属性,意思是关联
            contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')
        # 渲染模板
        context = {
            'categories': categories,
            'contents': contents,
        }
        return render(request, 'index.html', context)


class BannerView(View):
    """轮播图广告视图"""
    def get(self, request):
        # 获取状态为True的轮播图广告
        banners = Content.objects.filter(status=True, category__key='index_lbt').order_by('sequence')
        
        # 构造响应数据
        banner_list = []
        for banner in banners:
            # 获取完整的图片URL，确保包含FastDFS服务器前缀
            image_url = banner.image.url if banner.image else ''
            
            banner_list.append({
                'id': banner.id,
                'name': banner.title,
                'image': image_url,  # 使用完整的URL，包含FDFS_BASE_URL前缀
                'url': banner.url
            })
        
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'banners': banner_list})